/* eslint-disable no-console */
import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';
const { errorReport, getUrlByPromise } = _t;
// create an axios instance
const instance = axios.create({
  baseURL: '',
  timeout: 3000,
  withCredentials: true,
});

const reqlock = {};

// request interceptor
instance.interceptors.request.use(
  async function (config) {
    try {
      config.url = await getUrlByPromise(config.url);
    } catch (error) {
      errorReport({name:`获取动态域名报错 ${error.name}`,message:error.message,stack:error.stack,type:'js'});
    }
    if (config.method === 'post') {
      config.headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
      };
    }
    const reqLockKey = config.params && config.params.reqLockKey;
    if (!reqLockKey || !reqlock[reqLockKey]) {
      reqLockKey && (reqlock[reqLockKey] = true);
      return config;
    }

    return Promise.reject();
  },
  function (error) {
    // request error
    return Promise.reject(error);
  }
);

// response interceptor
instance.interceptors.response.use(
  function (response) {
    const reqLockKey = response.params && response.params.reqLockKey;
    if (reqLockKey) {
      reqlock[reqLockKey] = false;
    }
    return response.data;
  },
  function (error) {
    // response error
    errorReport({name:`接口响应错误，具体接口url：${error.config.url}`,message:error.message,stack:error.stack});
    Vue.prototype.$toast('请求异常，请重新刷新页面');
    return Promise.reject(error);
  }
);

// 全局过滤errorcode
const successFn = (response, url, params) => {
  const errorcode = response?.errorcode || response?.errorCode || response?.status_code || response?.code;
  // 没有权限
  if (response?.code === 401) {
    Vue.prototype.$toast(response.message);
  }
  if (errorcode) {
    errorReport({
      name: '接口errorCode报错',
      message: `url:${url},errorcode:${errorcode},params:${JSON.stringify(params)}`,
      stack: JSON.stringify(response),
    });
  }
  return response;
};

/**
 * @param {String} method Request method: get、post、delete、put
 * @param {String} url Request url
 * @param {Object} data Request param
 * @returns {Promise}
 */
export default function (method, url, lastUrl, data = null) {
  const newUrl = url + lastUrl;
  const reqFn = ()=>{
    const newMethod = method.toLowerCase();
    if (newMethod === 'post') {
      const config = {
        headers: {
          'Content-Type': 'application/json',
        },
      };
      return instance.post(newUrl, qs.stringify(data), config);
    } else if (newMethod === 'get') {
      return instance.get(newUrl, {
        params: data,
      });
    } else if (newMethod === 'delete') {
      return instance.delete(newUrl, {
        params: data,
      });
    } else if (newMethod === 'put') {
      return instance.put(newUrl, data);
    } else {
      return false;
    }
  }
  const result = reqFn();
  if(result){
    return result.then(response => successFn(response, newUrl, data));
  }else{
    return result;
  }
}
